package com.jsj.servlet.ch4;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/shoppingList")
public class ShoppingListServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		
		//获取会话对象
		HttpSession session=request.getSession();
		
		Map<String,Integer> car= (Map<String, Integer>) session.getAttribute("shoppingCar");
		
		if(car !=null && car.size()>0) {
			System.out.println("<p>您购买的书籍有：</p>");
			for(String bookName:car.keySet()) {
				out.println("<p>"+ bookName +","+car.get(bookName) +"本</p>");
			}
		}else {
			System.out.println("<p>您还没有购买书籍。</p>");
			
		}
		out.println("<p><a href='"+response.encodeRedirectURL("bookChoose.jsp")+"'>继续购买</a></p>");
		//response.sendRedirect("");
		
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
	
	public static void main(String[] args) {
		
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("java1", 2);
		map.put("java2", 1);
		map.put("java3", 4);
		map.put("java4", 3);
		map.put("java5", 4);
		map.put("java6", 6);
		
		for(String key:map.keySet()) {
			System.out.println("key:"+key+"\tvalue:"+map.get(key));
		}
		
		System.out.println("---------------------------------------------");
		
		for(Object value:map.values()) {
			System.out.println(value);
		}
		
		System.out.println("---------------------------------------------");
		
		 Set<Entry<String, Object>> s=map.entrySet();
		 Iterator<Entry<String, Object>>  it=s.iterator();
		 while(it.hasNext()) {
			 Entry<String, Object> entry=it.next();
			 System.out.println("key:"+entry.getKey()+"\tvalue:"+entry.getValue());
		 }
		
	}
	
	
	
}
